package com.shibida.shibidaProject.userInfo.controller;
import com.shibida.shibidaProject.userInfo.custom.CookerDetailInfo;
import com.shibida.shibidaProject.userInfo.custom.MyDishInfo;
import com.shibida.shibidaProject.userInfo.custom.OrderFood;
import com.shibida.shibidaProject.userInfo.custom.SimplyDishInfo;
import com.shibida.shibidaProject.userInfo.dao.CookerRepository;
import com.shibida.shibidaProject.userInfo.dao.DishRepository;
import com.shibida.shibidaProject.userInfo.dao.TagRepository;
import com.shibida.shibidaProject.userInfo.dao.UserInfoRepository;
import com.shibida.shibidaProject.userInfo.domain.*;
import org.apache.catalina.User;
import org.springframework.data.util.Pair;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/userBase")
@CrossOrigin
public class UserBaseController {
    @Resource
    private UserInfoRepository dao;
    @Resource
    private TagRepository tagDao;
    @Resource
    private CookerRepository cookerDao;
    @Resource
    private DishRepository dishDao;
    @GetMapping("/list")
    public List<UserVO> find(String sex, int _start, int _limit){
        List<UserVO> list = dao.queryBySex(sex, _start, _limit);
        return list;
    }

    // 获取所有数据
    @GetMapping("/allUser")
    public List<UserVO> findAllUser() {
        List<UserVO> list = dao.queryAll();
        for (UserVO userItem : list) {
            String tagIdStr = userItem.getTags();
            userItem.setTags(tagIdStrToCorrectTag(tagIdStr));
        }
        return list;
    }
    //厨师信息界面
    @GetMapping("/message")
    public CookerDetailInfo getCookerDetail(int id) {
        List<CookerDetailVO> list = cookerDao.queryAllById(id);
        CookerDetailInfo result = new CookerDetailInfo();
        if (list.size() != 0) {
            result.setCookerDetailVO(list.get(0));
        }
        UserVO user = dao.queryAllById(id);
        String tagNames = tagIdStrToCorrectTag(user.getTags());
        user.setTags(tagNames);
        result.setUserVO(dao.queryAllById(id));
        List<OrderFood> foodInfo = new ArrayList<>();
        List<List<String>> dishRet = getNameAndUrlFromDish(result.getCookerDetailVO().getDish());
        String[] unitPrice = result.getCookerDetailVO().getPrice().split("\\|");
        int index = 0;
        for(List<String> item : dishRet) {
            if(item.size() == 3) {
                OrderFood infoItem = new OrderFood();
                infoItem.setFoodName(item.get(0));
                infoItem.setPicUrl(item.get(1));
                infoItem.setPrice(Float.parseFloat(index < unitPrice.length ? unitPrice[index] : "0"));
                infoItem.setFoodId(Integer.parseInt(item.get(2)));
                index++;
                foodInfo.add(infoItem);
            }
        }
        result.getCookerDetailVO().setFoodsInfo(foodInfo);
        return result;
    }
    /**

     * 分页查询
     * @param _start 开始序号
     * @param _limit 查询条数
     * @return 查询结果
     */
    @GetMapping("/allPageUser")
    public List<UserVO> find(int _start, int _limit) {
        List<UserVO> list = dao.queryPageAll(_start, _limit);
        for (UserVO userItem : list) {
            String tagIdStr = userItem.getTags();
            userItem.setTags(tagIdStrToCorrectTag(tagIdStr));
        }
        return list;
    }
    @PatchMapping("/updateUserInfo")
    public boolean patchMethod(@RequestBody UserVO user) {
        if(user.getTags().startsWith("|")) {
            String tempTag = user.getTags().substring(1);
            user.setTags(tempTag);
        }
        user.setTags(tagStrToStrTag(user.getTags()));
        dao.updateAllById(user.getUserName(), String.valueOf(user.getSex()), user.getAge(),user.getTel(), user.getHeadIconUrl(), user.getLocate(), user.getIdCard(), user.getTags(), user.getId());
        return true;
    }

    @PatchMapping("/updateCookerDetailInfo")
    public boolean updateCookerDetailInfo(@RequestBody SimplyDishInfo info) {
        if(info.getData().size() == 0) {
            return false;
        }
        StringBuilder dishName = new StringBuilder();
        StringBuilder dishPrice = new StringBuilder();
        int cutIndex = 0;
        for(MyDishInfo dishInfoItem : info.getData()) {
            dishName.append(dishInfoItem.getDishName());
            dishPrice.append(dishInfoItem.getDishPrice());

            if(cutIndex != info.getData().size() - 1) {
                dishName.append('|');
                dishPrice.append('|');
            }
            cutIndex++;
        }
        cookerDao.updateNameAndPriceById(dishName.toString(), dishPrice.toString(), info.getId());
        return true;
    }

    @GetMapping("/userDataById")
    public UserVO find(int id) {
        UserVO info = dao.queryAllById(id);
        info.setTags(tagIdStrToCorrectTag(info.getTags()));
        return info;
    }

    @GetMapping("/getAllDish")
    public List<DishVO> getAllDish() {
        return dishDao.getAll();
    }

    /**
     * 返回数据库表的项数
     * @return 项数
     */
    @GetMapping("/allUserCount")
    public String allUserCount() {
        return String.valueOf(dao.count());
    }

    /**
     * 通过key搜索用户表
     * @param key key可以是用户名、地址、菜系的str
     * @return 返回不重复的用户列表
     */
    @GetMapping("/searchUser")
    public List<UserVO> searchUser(String key) {
        Set<UserVO> result = new HashSet<>();
        // 搜索名字
        List<UserVO> usersByUserName = dao.queryAllByUserName(key);
        for (UserVO userItem : usersByUserName) {
            String tagIdStr = userItem.getTags();
            userItem.setTags(tagIdStrToCorrectTag(tagIdStr));
        }
        // 搜索地址
        List<UserVO> usersByLocate = dao.queryAllByLocate(key);
        for (UserVO userItem : usersByLocate) {
            String tagIdStr = userItem.getTags();
            userItem.setTags(tagIdStrToCorrectTag(tagIdStr));
        }
        // 搜索菜系

        // 判断关键字是否包含菜系， 不包含不检索菜系
        List<TagVO> tags = tagDao.findAll();
        List<UserVO> userByTag = new ArrayList<>();
        boolean haveCook = false;   //搜索关键字有菜系
        for(TagVO item : tags) {
            if(Objects.equals(key, tagDao.getTagBy(item.getId()))) {
                haveCook = true;
                break;
            }
        }
        // 查询是否有匹配的tag
        if(haveCook) {
            List<UserVO> allUser = findAllUser();
            for(UserVO userItem : allUser) {
                String[] tagArray = userItem.getTags().split("\\|");
                for(String tag : tagArray) {
                    if(Objects.equals(tag, key)) {
                        userByTag.add(userItem);
                        break;
                    }
                }
            }
        }

        // 将查询的输入存入Set防止重读
        result.addAll(usersByUserName);
        result.addAll(usersByLocate);
        result.addAll(userByTag);
        return new ArrayList<>(result);
    }

    @PostMapping("/add")
    @ResponseBody
    public UserVO add(@RequestBody UserVO studentVO){
        System.out.println("*********");
        System.out.println(studentVO.getAge());
        System.out.println("*********");
        UserVO stu = dao.save(studentVO);
        return stu;
    }
    //登录
    @PostMapping("/login")
    @ResponseBody
    public UserVO match(@RequestBody UserVO User){
        String name=User.getUserName();
        UserVO user = dao.Match(name);
        return user;
    }
    // 注册
    @PostMapping("/register")
    @ResponseBody
    public Boolean insert(@RequestBody UserVO User){
        String name=User.getUserName();
        UserVO user1 = dao.Match(name);
        if (user1 == null)
        {
            UserVO user = dao.save(User);

            CookerDetailVO cookerDetailVO = new CookerDetailVO();
            cookerDetailVO.setId(user.getId());
            cookerDetailVO.setDish("1");
            cookerDetailVO.setPrice("1");
            cookerDetailVO.setScore(1f);
            cookerDetailVO.setService_number(0);
            cookerDetailVO.setFood_show1("/");
            cookerDetailVO.setFood_show2("/");
            cookerDetailVO.setFood_show3("/");
            cookerDetailVO.setFood_show4("/");
            cookerDao.insertDish(cookerDetailVO.getId(), cookerDetailVO.getDish(), cookerDetailVO.getPrice(), cookerDetailVO.getScore(), cookerDetailVO.getService_number(), cookerDetailVO.getFood_show1(), cookerDetailVO.getFood_show2(), cookerDetailVO.getFood_show3(), cookerDetailVO.getFood_show4());

            return true;
        }
        return false;
    }

    /**
     * 将tag的id字符串转换为str字符串
     * @param idStr id字符串
     * @return 转换后的tag字符串
     */
    public String tagIdStrToCorrectTag(String idStr) {

        if(null==idStr){
            return "";
        }
        String[] tagIdArray = idStr.split("\\|");
        ArrayList<String> correctTagArray = new ArrayList<>();
        for (String tagIdStr : tagIdArray) {
            int id = Integer.parseInt(tagIdStr);
            correctTagArray.add(tagDao.getTagBy(id));
        }
        StringBuilder correctBuffer = new StringBuilder();
        int size = correctTagArray.size();
        for (int i = 0; i < size; i++) {
            correctBuffer.append(correctTagArray.get(i));
            if (i != size - 1) {
                correctBuffer.append('|');
            }
        }
        return correctBuffer.toString();
    }
    public String tagStrToStrTag(String tagStr) {
        if(null==tagStr){
            return "";
        }
        String[] tagIdArray = tagStr.split("\\|");
        ArrayList<String> correctTagArray = new ArrayList<>();
        for (String tagIdStr : tagIdArray) {
            correctTagArray.add(tagDao.getTagStr(tagIdStr));
        }
        StringBuilder correctBuffer = new StringBuilder();
        int size = correctTagArray.size();
        for (int i = 0; i < size; i++) {
            correctBuffer.append(correctTagArray.get(i));
            if (i != size - 1) {
                correctBuffer.append('|');
            }
        }
        return correctBuffer.toString();
    }

    public List<List<String>> getNameAndUrlFromDish(String dishStr) {
        String[] dishIds = dishStr.split("\\|");
        List<List<String>> result = new ArrayList<>();
        for(String dishId : dishIds) {
            List<DishVO> dishRet = dishDao.getAllById(Integer.parseInt(dishId));
            if(dishRet.size() != 0) {
                List<String> item = new ArrayList<>();
                String dishName = dishRet.get(0).getDish_name();
                String dishUrl = dishRet.get(0).getDish_url();
                item.add(dishName);
                item.add(dishUrl);
                item.add(dishId);
                result.add(item);
            }
        }
        return result;
    }
}
